<template>
  <div>
    <el-form ref="form" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="用户角色" prop="roleId">
        <el-select v-model="form.roleId" placeholder="请选择角色" :disabled="isDisabled">
          <el-option v-for="(item, index) in roleList" :key="index" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户名称" prop="tenantName">
        <el-input
          placeholder="请填写用户名称"
          v-model="form.tenantName"
          maxlength="24"
          :disabled="isDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item label="登陆账号" prop="loginAccount">
        <el-input
          placeholder="请填写登陆账号"
          v-model="form.loginAccount"
          maxlength="11"
          :disabled="isDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item label="关联项目" prop="relationApp">
        <el-select v-model="form.relationApp" multiple :disabled="isDisabled" @change="changeProject">
          <el-option
            v-for="(item, index) in projectList"
            :key="index"
            :label="item.name"
            :value="item.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据范围" prop="relationProduct">
        <el-select v-model="form.relationProduct" multiple @change="changeProduct" clearable :disabled="isDisabled">
          <el-option
            v-for="(item, index) in productionList"
            :key="index"
            :label="item.name"
            :value="item.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status" :disabled="isDisabled">
          <el-radio :label="item.value" v-for="item in STATUS_LIST" :key="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" size="small" @click="save()" v-if="!isDisabled">保存</el-button>
        <el-button size="small" @click="cancel()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { STATUS_LIST } from '@/constants/baseModel.js'
import { phoneReg } from '@/utils/validator'
const isPhone = (rule, value, callback) => {
  if (!value) callback(new Error('请输入手机号'))
  else {
    if (!phoneReg(value)) return callback(new Error('请输入正确的手机号'))
    callback()
  }
}
export default {
  name: 'accountAddEdit',
  data() {
    return {
      STATUS_LIST,
      roleList: [],
      // 关联项目
      projectList: [],
      // 数据范围
      productionList: [],
      rules: {
        roleId: [{ required: true, message: '请选择角色' }],
        tenantName: [{ required: true, message: '请填写用户名称' }],
        loginAccount: [{ required: true, validator: isPhone }],
        relationApp: [{ required: true, message: '请选择关联项目' }],
        relationProduct: [{ required: true, message: '请选择数据范围' }],
      },
      form: {
        // 用户id
        roleId: '',
        // 用户名称
        tenantName: '',
        // 登陆账号
        loginAccount: '',
        // 关联项目
        relationAppCode: '',
        // 展示关联项目使用
        relationApp: [],
        // 展示数据范围使用
        relationProduct: [],
        // 数据范围
        relationProductCode: '',
        // 状态
        status: '1',
      },
    }
  },
  computed: {
    isDisabled() {
      return this.$route.query.title && this.$route.query.title === 'watch' ? true : false
    },
  },
  methods: {
    async changeProject(val) {
      console.log(val)
      await this.getProductListRequest(val)
    },
    changeProduct(val) {
      if (val.includes('')) {
        const allCodes = this.productionList.filter(item => item.code !== '')
        this.form.relationProduct = allCodes.map(item => item.code)
        return
      }
    },
    save() {
      this.$refs['form'].validate(async valid => {
        if (!valid) return
        const params = {
          roleId: this.form.roleId,
          tenantName: this.form.tenantName,
          loginAccount: this.form.loginAccount,
          relationAppCode: this.form.relationApp.toString(),
          relationProductCode: this.form.relationProduct.toString(),
          status: this.form.status,
        }
        await this.saveRequest(params)
        this.$router.back(-1)
      })
    },
    cancel() {
      this.$router.back(-1)
    },
    async saveRequest(params) {
      const url = this.$route.query.userId ? `/accounts/${this.$route.query.userId}/update` : '/accounts/add'
      const method = this.$route.query.userId ? 'put' : 'post'
      await this.$http[method](url, params)
    },
    async getDetailRequest() {
      const res = await this.$http.get(`/accounts/${this.$route.query.userId}`)
      this.form.roleId = res.roleId
      this.form.tenantName = res.tenantName
      this.form.loginAccount = res.loginAccount
      this.form.relationApp = res.relationAppCode.split(',')
      this.form.relationProduct = res.relationProductCode.split(',')
      this.form.status = res.status
      await this.getProductListRequest(res.relationAppCode)
    },
    async getRoleRequest() {
      this.roleList = await this.$http.get('/roles/list')
    },
    async getProductListRequest(codes) {
      const productionList = await this.$http.get('/products/list', {
        params: {
          appCodes: codes.toString(),
        },
      })
      this.productionList = [{ name: '全部', code: '' }, ...productionList]
    },
    async getSourceListRequest() {
      this.projectList = await this.$http.get(`/app/list`)
    },
  },
  mounted() {
    if (this.$route.query.userId) {
      this.getDetailRequest()
    }
    this.getRoleRequest()
    this.getSourceListRequest()
    // this.getProductListRequest()
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
